package com.wthink.newMain.main

import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.annotation.RequiresApi
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.wthink.card.Thread.PersecProcThread
import com.wthink.card.Thread.SerialFrameProcThread
import com.wthink.card.Thread.SocketFrameProcThread
import com.wthink.card.models.ShdFrameBundle
import com.wthink.hzgj.Constants
import com.wthink.hzgj.R
import com.wthink.hzgj.data.domain.BusDispatch
import com.wthink.hzgj.databinding.FragmentNewHomeBinding
import com.wthink.hzgj.util.CustomKeyEventProc
import com.wthink.hzgj.util.`interface`.LineCallBack
import com.wthink.hzgj.util.`interface`.SchedleRefuseCallBack
import com.wthink.newMain.main.viewmodel.NewHomemodel
import com.wthink.newMain.view.ChangeAutoPlayDialog
import com.wthink.newMain.view.ChangeUpLineDialog
import com.wthink.newMain.view.LoginCardDialog
import com.wthink.newMain.view.WaitSchedleDialog
import com.wthink.newMain.view.changeLine.ChangeLineDialogX
import com.wthink.newMain.view.changeLine.FixLineDialogViewmodel
import kotlinx.android.synthetic.main.fragment_new_home.*
import java.lang.StringBuilder
import java.nio.ByteBuffer

@RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
class NewHomeFragment : Fragment() {

    var serialFrameProcThread: SerialFrameProcThread? = null
    var socketFrameProcThread: SocketFrameProcThread? = null
    var persecProcThread: PersecProcThread? = null

    private val changeUpLineDialog: ChangeUpLineDialog by lazy {
        ChangeUpLineDialog(context!!)
    }

    private val waitSchedleDialog: WaitSchedleDialog by lazy {
        WaitSchedleDialog(context!!)
    }

    private val changeAutoPlayDialog: ChangeAutoPlayDialog by lazy {
        ChangeAutoPlayDialog(context!!)
    }

    private val changeLineDialogX: ChangeLineDialogX by lazy {
        ChangeLineDialogX(activity!!)
    }

    private val loginCardDialog: LoginCardDialog by lazy {
        LoginCardDialog(activity!!)
    }

    private val fixLineDialogViewmodel by viewModels<FixLineDialogViewmodel>()

    private val viewModel by viewModels<NewHomemodel>()

    private lateinit var binding: FragmentNewHomeBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DataBindingUtil.inflate(
            inflater,
            R.layout.fragment_new_home,
            container,
            false
        )
        binding.viewModel = viewModel
        binding.lifecycleOwner = this
        binding.fixLineDialogViewmodel = fixLineDialogViewmodel
        return binding.root
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initSocketThread()

        viewModel.start()

        viewModel.setRefuseCallBack(object : SchedleRefuseCallBack {
            override fun callBack(content: String) {
                activity?.runOnUiThread {
                    waitSchedleDialog.show()
                    if (content == "0") {
                        waitSchedleDialog.setContent("拒绝")
                    } else if (content == "1") {
                        waitSchedleDialog.setContent("同意")
                    }
                    waitSchedleDialog.setOnclickListener(View.OnClickListener {
                        when (it?.id) {
                            R.id.close -> {
                                waitSchedleDialog.dismiss()
                            }
                        }
                    })
                }
            }
        })

        binding.tvUpDown.setOnClickListener {
            changeUpLineDialog.show()
            changeUpLineDialog.setOnclickListener(View.OnClickListener { v ->
                when (v?.id) {
                    R.id.commit -> {
                        changeUpLineDialog.dismiss()
                        val iv1 = changeUpLineDialog.findViewById<ImageView>(R.id.iv1)
                        if (iv1.isSelected) {
                            binding.tvUpDown.text = "上行"
                        } else {
                            binding.tvUpDown.text = "下行"
                        }

                        viewModel.loadUpdir(viewModel.line.value!!.id,iv1.isSelected)
                    }
                    R.id.back -> {
                        changeUpLineDialog.dismiss()
                    }
                    R.id.iv1 -> {
                        changeUpLineDialog.setBackGround(v.id)
                    }
                    R.id.iv2 -> {
                        changeUpLineDialog.setBackGround(v.id)
                    }
                }
            })
        }

        binding.tvAuto.setOnClickListener {
            changeAutoPlayDialog.show()
            changeAutoPlayDialog.setOnclickListener(View.OnClickListener { v ->
                when (v?.id) {
                    R.id.commit -> {
                        changeAutoPlayDialog.dismiss()
                        val iv1 = changeAutoPlayDialog.findViewById<ImageView>(R.id.iv1)
                        if (iv1.isSelected) {
                            binding.tvAuto.text = "自动"
                        } else {
                            binding.tvAuto.text = "手动"
                        }
                    }
                    R.id.back -> {
                        changeAutoPlayDialog.dismiss()
                    }
                    R.id.iv1 -> {
                        changeAutoPlayDialog.setBackGround(v.id)
                    }
                    R.id.iv2 -> {
                        changeAutoPlayDialog.setBackGround(v.id)
                    }
                }
            })
        }

        binding.tvLine.setOnClickListener {
            changeLineDialogX.show()
            val list = viewModel.lineList.value?.list
            changeLineDialogX.setList(tv_line.text.toString(), list)
            changeLineDialogX.setLineCall(object : LineCallBack {
                override fun callBack(lineNum: String, lineId: String) {
                    if (lineNum.isNotEmpty()) {
                        binding.tvLine.text = lineNum
                        viewModel.loadStationList(lineId, lineNum, viewModel.upDir.value!!)
                    }
                }
            })
        }
    }

    private val uiHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            try {
                when (msg.what) {
                    Constants.UI_RC522 -> {
                        Log.d("TAGGGGGGG", "刷卡ID-->" + SocketFrameProcThread.mStrCardId)
                        showLoginDialog(SocketFrameProcThread.mStrCardId)
                        val frameBuf = ByteBuffer.allocate(20)
                        if (SocketFrameProcThread.mStrCardId != null) {
                            frameBuf.put(0x1b.toByte())
                            frameBuf.put(8.toByte())
                            frameBuf.put(SocketFrameProcThread.mStrCardId.toString().toByteArray())
                            frameBuf.put(0x1c.toByte())
                            frameBuf.put(0x00.toByte())
                        }
                    }
                    else -> super.handleMessage(msg)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun showLoginDialog(mStrCardId: StringBuilder?) {
        loginCardDialog.show()
        loginCardDialog.setContent(mStrCardId.toString())
        viewModel.cardId.postValue(mStrCardId.toString())
    }

    private fun initSocketThread() {
        socketFrameProcThread = SocketFrameProcThread(context, uiHandler)
        socketFrameProcThread!!.start()
        persecProcThread =
            PersecProcThread(context, socketFrameProcThread, serialFrameProcThread, uiHandler)
        persecProcThread!!.start()
        val frameBuf = ByteBuffer.allocate(3)
        if (socketFrameProcThread != null) {
            frameBuf.clear()
            frameBuf.put(5.toByte())
            socketFrameProcThread!!.SendToMainBoardNormalFrm(
                ShdFrameBundle.B_SOCKET_FRAME_03,
                frameBuf.array(),
                1,
                ShdFrameBundle.A_SOCKET_MODEL_01
            )
        }
    }

    fun setkeyDown(scanCode: Int) {
        when (scanCode) {
            CustomKeyEventProc.KEY_F6 -> {
                viewModel.leftBus()
            }

            CustomKeyEventProc.KEY_F8 -> {
                viewModel.rightBus()
            }
            CustomKeyEventProc.CUSTOM_KEYCODE_PLAY -> {
                viewModel.playStation()
            }
        }
    }

    fun busDispatch(busDispatch: BusDispatch?) {
        viewModel.updateLine(busDispatch)
    }

    override fun onDestroy() {
        if (serialFrameProcThread != null) {
            serialFrameProcThread!!.interrupt()
            try {
                serialFrameProcThread!!.join()
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }
            serialFrameProcThread = null
        }
        if (socketFrameProcThread != null) {
            socketFrameProcThread!!.interrupt()
            try {
                socketFrameProcThread!!.join()
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }
            socketFrameProcThread = null
        }

        if (persecProcThread != null) {
            persecProcThread!!.interrupt()
            try {
                persecProcThread!!.join()
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }
            persecProcThread = null
        }
        super.onDestroy()
    }
}